<template>
  <div class="table-container">
    <i-table
      ref="table"
      v-loading="loading"
      :data="dataSource"
      :columns="columns"
      :pagination="pagination"
      :total="total"
      @pagination-change="handlePageChange"
      :span-method="spanMethod"
      small
      class="table-wrapper"
      layout="sizes, prev, pager, next, jumper"
    >
      <template v-for="item in columns">
        <slot v-if="item.slot" :name="item.slot" :slot="item.slot" />
      </template>
    </i-table>
    <div class="table-statistics">
      当前第{{ pagination.currentPage }}页，共{{ maxPageCount }} 页, 共{{
        total
      }}条数据
    </div>
  </div>
</template>
<script>
export default {
  name: 'CTable',
  props: {
    spanMethod: {
      type: Function,
    },
    loading: {
      type: Boolean,
      default: false,
    },
    dataSource: {
      type: Array,
      default: () => [],
    },
    columns: {
      type: Array,
      required: true,
    },
    total: {
      type: Number,
      required: true,
    },
  },
  computed: {
    maxPageCount() {
      return Math.ceil(this.total / this.pagination.pageSize)
    },
  },
  mounted() {
    this.refresh()
  },
  data() {
    return {
      pagination: {
        currentPage: 1,
        pageSize: 10,
        background: false,
      },
    }
  },
  methods: {
    handlePageChange({ type, val }) {
      this.pagination[type] = val
      type === 'currentPage' &&
        val > this.maxPageCount &&
        (this.pagination.currentPage = this.maxPageCount)
      type === 'pageSize' && (this.pagination.currentPage = 1)
      this.$emit('getDataSource', { ...this.pagination })
    },
    getDataSource() {
      this.$emit('getDataSource', { ...this.pagination })
    },
    refresh() {
      // this.pagination.currentPage = 1
      this.getDataSource()
    },
  },
}
</script>
<style lang="scss" scoped>
.table-container {
  background: #fff;
  width: 100%;
  padding: 20px;
  border: none;
  color: #100625;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
  border-radius: 4px;
}

.table-statistics {
  padding-top: 12px;
}
</style>
